<template>
    <el-main>
        <!-- 搜索栏 -->
        <el-form :model="pageSearchForm" :inline="true" size="default">
            <el-form-item>
                <el-input placeholder="姓名" v-model="pageSearchForm.nickName"></el-input>
            </el-form-item>
            <el-form-item>
                <el-input placeholder="手机号" v-model="pageSearchForm.phone"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button icon="Search" @click="onSearch">搜索</el-button>
                <el-button icon="Close" type="danger" plain @click="onReset">重置</el-button>
                <el-button v-permission="['sys:user:add']" icon="Plus" type="primary" @click="onNewAdd">
                    新增
                </el-button>
            </el-form-item>
        </el-form>

        <!-- 表格 -->
        <el-table :height="tableHeight" :data="tableData" border stripe>
            <el-table-column prop="nickName" label="姓名"></el-table-column>
            <el-table-column prop="sex" label="性别">
                <template #default="scope">
                    <el-tag v-if="scope.row.sex == '0'" type="primary" size="default" effect="dark">男</el-tag>
                    <el-tag v-if="scope.row.sex == '1'" type="success" size="default" effect="dark">女</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="phone" label="电话"></el-table-column>
            <el-table-column prop="username" label="账号"></el-table-column>
            <el-table-column min-width="168"
                v-if="global.$hasPerm(['sys:user:edit', 'sys:user:delete', 'sys:user:resetPassword'])" align="center"
                label="操作">
                <template #default="scope">
                    <el-button v-permission="['sys:user:edit']" type="primary" size="small"
                        @click="onEdit(scope.row)">编辑 </el-button>
                    <el-button :disabled="userSotre.getIsAdmin && scope.row.isAdmin === '1'"
                        v-permission="['sys:user:delete']" type="danger" size="small"
                        @click="onDelete(scope.row)">删除</el-button>
                    <el-button v-permission="['sys:user:resetPassword']" type="danger" plain size="small"
                        @click="oneResetPassword(scope.row)">重置密码</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination @size-change="sizeChange" @current-change="currentChange"
            :current-page.sync="pageSearchForm.currentPage" :page-sizes="[10, 20, 30, 50, 60, 80, 100]"
            :page-size="pageSearchForm.pageSize" layout="total, sizes, prev, pager, next, jumper"
            :total="pageSearchForm.total" background>
        </el-pagination>

        <!-- 新增编辑 -->
        <SysDialog :title="dialog.title" :width="dialog.width" :visible="dialog.visible" @on-close="onDialogClose"
            @on-confirm="onSubmit">
            <template #content>
                <el-form :model="userForm" ref="userFormRef" :rules="rules" label-width="80px" :inline="false"
                    size="default">
                    <el-row>
                        <el-col :span="12" :offset="0">
                            <el-form-item prop="nickName" label="姓名">
                                <el-input v-model="userForm.nickName"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12" :offset="0">
                            <el-form-item prop="sex" label="性别">
                                <el-radio-group v-model="userForm.sex">
                                    <el-radio :label="'0'">男</el-radio>
                                    <el-radio :label="'1'">女</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12" :offset="0">
                            <el-form-item prop="phone" label="电话">
                                <el-input v-model="userForm.phone"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12" :offset="0">
                            <el-form-item prop="email" label="邮箱">
                                <el-input v-model="userForm.email"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12" :offset="0">
                            <el-form-item prop="username" label="账户">
                                <el-input v-model="userForm.username"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12" :offset="0">
                            <el-form-item prop="password" label="密码">
                                <el-input :disabled="dialogType === 'edit'"
                                    :type="dialogType === 'edit' ? 'password' : 'text'"
                                    v-model="userForm.password"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12" :offset="0">
                            <el-form-item prop="roleId" label="角色">
                                <SelectChecked ref="roleSelectRef" placeholder="选择用户角色" :options="roleSelectOptions"
                                    @selected="onRoleSelectChange">
                                </SelectChecked>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </template>
        </SysDialog>
    </el-main>
</template>

<script setup lang="ts">
import { nextTick, onMounted, reactive, ref } from "vue"
import SysDialog from "@/components/SysDialog.vue"
import useDialog from '../../../hooks/useDialog'
import { ElMessage, type FormInstance } from "element-plus"
import SelectChecked from "@/components/SelectChecked.vue"
import type { SelectRoleOptionVO } from "../../../api/role/RoleModel"
import { RoleApi } from "../../../api/role"
import { SysUserApi } from "../../../api/user"
import type { SysUserVO, UserPageQuery, UserReq } from "../../../api/user/UserModel"
import useInstance from '../../../hooks/useInstance'
import { useUserStore } from "../../../store/user"

const userSotre = useUserStore()
// 表单ref属性
const userFormRef = ref<FormInstance>()
const roleSelectRef = ref()
// 弹框属性
const { dialog, onDialogClose, onDialogShow } = useDialog()
// 搜索栏绑定对象
const pageSearchForm = reactive<UserPageQuery>({
    phone: '',
    nickName: '',
    currentPage: 1,
    pageSize: 10,
    total: 10
})
// 新增绑定对象
const userForm = reactive<UserReq>({
    userId: '',
    username: '',
    password: '',
    phone: '',
    email: '',
    sex: '',
    nickName: '',
    roleId: ''
})
// 表单验证规则
const rules = reactive({
    nickName: [
        {
            required: true,
            trigger: ["blur", "change"],
            message: "请输入姓名",
        },
    ],
    sex: [
        {
            required: true,
            trigger: ["blur", "change"],
            message: "请选择性别",
        },
    ],
    phone: [
        {
            required: true,
            trigger: ["blur", "change"],
            message: "请输入电话",
        },
    ],
    username: [
        {
            required: true,
            trigger: ["blur", "change"],
            message: "请输入账户",
        },
    ],
    password: [
        {
            required: true,
            trigger: ["blur", "change"],
            message: "请输入密码",
        },
    ],
    roleId: [
        {
            required: true,
            trigger: ["blur", "change"],
            message: "请选择角色",
        },
    ]
})

let roleSelectOptions = ref<SelectRoleOptionVO[]>([])
// 勾选的值
const onRoleSelectChange = (value: Array<string | number>) => {
    userForm.roleId = value.join(',')
}
const queryRoleOptionList = async () => {
    const res = await RoleApi.listRoleOption()
    if (res && res.code === 200) {
        roleSelectOptions.value = res.data
    }
}

// 搜索
const onSearch = () => {
    queryTableData()
}
// 重置
const onReset = () => {
    pageSearchForm.currentPage = 1
    pageSearchForm.pageSize = 10
    pageSearchForm.nickName = ''
    pageSearchForm.phone = ''
    queryTableData()
}

const tableData = ref([])
const queryTableData = async () => {
    const res = await SysUserApi.page(pageSearchForm)
    tableData.value = res.data.records
    pageSearchForm.total = res.data.total
}

// 页容量改变时触发
const sizeChange = (size: number) => {
    pageSearchForm.pageSize = size
    queryTableData()
}
// 页数改变时触发
const currentChange = (page: number) => {
    pageSearchForm.currentPage = page
    queryTableData()
}

/**
 * 点击删除按钮后回调
 */
const { global } = useInstance()
const onDelete = async (row: SysUserVO) => {
    const confirm = await global.$jagochanConfirm(`确定删除【${row.nickName}】用户吗？`)
    if (confirm) {
        let res = await SysUserApi.delete(row.userId)
        if (res && res.code == 200) {
            ElMessage.success(res.msg)
            queryTableData()
        }
    }
}

const oneResetPassword = async (row: SysUserVO) => {
    const now = new Date()
    const newPwd = now.getFullYear() + '' + row.userId + '888'

    const confirm = await global.$jagochanConfirm(`确定要重置用户【${row.nickName}】的密码吗？重置后的密码是【${newPwd}】`)
    if (confirm) {
        let res = await SysUserApi.resetPassword(row.userId)
        if (res && res.code == 200) {
            ElMessage.success(res.msg)
        }
    }
}

let dialogType: 'newAdd' | 'edit' = 'newAdd'
const onEdit = (row: SysUserVO) => {
    dialogType = 'edit'

    dialog.title = "编辑用户"
    nextTick(async () => {
        const roleIdList = await queryRoleIdsByUserId(row.userId)
        roleSelectRef.value.echo(roleIdList)
        row.roleId = roleIdList.join(',')
        // 回显数据
        Object.assign(userForm, row)
    })
    // 清空表单
    userFormRef.value?.resetFields()
    // 显示弹框
    onDialogShow()
}

// 新增按钮
const onNewAdd = () => {
    dialog.title = '新增用户'
    dialogType = 'newAdd'
    userForm.userId = ''
    nextTick(() => {
        userFormRef.value?.resetFields()
        roleSelectRef.value.clearSelectedOptions()
    })
    // 显示弹框
    onDialogShow()
}
// 提交表单
const onSubmit = () => {
    // 验证表单
    userFormRef.value?.validate(async (valid) => {
        if (valid) {
            let res = null

            if (dialogType === 'newAdd') {
                res = await SysUserApi.newAdd(userForm)
            } else {
                res = await SysUserApi.edit(userForm)
            }

            if (res && res.code === 200) {
                ElMessage.success(res.msg)
                queryTableData()
                onDialogClose()
            }
        }
    })
}

const queryRoleIdsByUserId = async (userId: string | number) => {
    const res = await SysUserApi.roleIds(userId)
    if (res && res.code === 200) {
        return res.data
    }
}

const tableHeight = ref(0)
onMounted(() => {
    nextTick(() => {
        tableHeight.value = window.innerHeight - 230
    })
    queryRoleOptionList()
    queryTableData()
})
</script>

<style scoped></style>
